﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Web
{
    public static class QueryableExtension
    {
        public static PageDto<T> Paging<T>(this IQueryable<T> query, int limit, int offset)
        {
            int total;
            var page = Paging(query, limit, offset, out total);
            return new PageDto<T>()
            {
                total = total,
                rows = page.ToList()
            };
        }
        public static IEnumerable<T> Paging<T>(this IQueryable<T> query, int limit, int offset, out int total)
        {
            Expression<Func<T, string>> order = null;
            return Paging(query, limit, offset, order, false, out total);
        }
        public static IEnumerable<T> Paging<T, TResult>(this IQueryable<T> query, int limit, int offset, Expression<Func<T, TResult>> orderByProperty, bool isAscendingOrder, out int rowsCount)
        {
            if (orderByProperty != null)
            {
                if (isAscendingOrder)
                    query = query.OrderBy(orderByProperty);
                else
                    query = query.OrderByDescending(orderByProperty);
            }
            rowsCount = query.Count();
            return query.Skip(offset).Take(limit);
        }
    }
    public class PageDto<T>
    {
        [JsonProperty("rows")]
        public IList<T> rows { get; set; }
        [JsonProperty("total")]
        public int total { get; set; }

    }
    public class QueryListModel
    {
        public string Sort { get; set; }

        [JsonProperty("offset")]
        [Display(Name = "offset")]
        public int Offset { get; set; } = 0;
        [JsonProperty("limit")]
        [Display(Name = "limit")]
        public int Limit { get; set; }

        public QueryListModel()
        {
            Offset = Int32.MaxValue;
            Limit = 1;
        }
    }
}
